package com.tolbahady.android.game;

import java.util.ArrayList;
import java.util.List;

public class TabelGame {
	private static TabelGame game;
	final int POINT_PER_SERV = 2;
	final int NUMBER_POINTS = 11;
	private Player[] players;
	private Player player2;
	private List<Serv> servs;
	private boolean gameEnd = false;
	Serv currentServ;
	private Player winer;
	public TabelGame(Player player1, Player player2) {
		super();
		this.players = new Player[2];
		this.players[0] = player1;
		this.players[1] = player2;
		servs = new ArrayList<TabelGame.Serv>();
		currentServ = new Serv(player1);
		servs.add(currentServ);
	}
	public void newPoint(int i){
		if (gameEnd) return;
		currentServ.addPoint(new Point(players[i]));
		if(getPlayerScore(0) >= NUMBER_POINTS  ){
			gameEnd = true;
			winer = players[0];
			return;
		}else if(getPlayerScore(1) >= NUMBER_POINTS  ){
			gameEnd = true;
			winer = players[1];
			return;
		}
		if(currentServ.getPoints()==POINT_PER_SERV)
			switchPlayers();
	}
	public static TabelGame startGame(){
		if(game != null) return game;
		if(PlayersList.getPlayers().size() < 2) return null;
		return new TabelGame(PlayersList.getPlayers().get(0),
				PlayersList.getPlayers().get(1));
	}
	public void switchPlayers(){
		if(currentServ.getServer().equals(players[0]))
			currentServ = new Serv(players[1]);
		else
			currentServ = new Serv(players[0]);
		servs.add(currentServ);
	}
	public int getPlayerScore(int i){
		int sum = 0;
		for(Serv s: servs)
			sum += s.getPoints(players[i]);
		return sum;
	}
	public Player[] getPlayers() {
		return players;
	}
	public int getCurrentServer() {
		return currentServ.getServer().equals(players[0])? 0 : 1;
	}
	public List<Serv> getServs() {
		return servs;
	}
	public boolean isGameEnd() {
		return gameEnd;
	}
	
	public class Serv{
		private List<Point> points;
		private Player server;
		public Serv(Player server) {
			super();
			this.server = server;
			points = new ArrayList<Point>();
		}
		public int getPoints(Player player) {
			int sum = 0;
			for(Point p : points)
				sum += p.getPlayer().equals(player) ? 1 : 0;
			return sum;
		}
		public void addPoint(Point p){
			points.add(p);
		}
		public int getPoints(){
			return points.size();
		}
		public Player getServer() {
			return server;
		}
	}
	public class Point{
		private Player player;
		public Point(Player player) {
			super();
			this.player = player;
		}
		public Player getPlayer() {
			return player;
		}
	}
	public Player getWiner() {
		
		return winer;
	}
}
